package com.qst.rongxiaoserver.common;

import com.auth0.jwt.exceptions.JWTVerificationException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

// 拦截器  拦截所有请求  验证token是否有效
// 拦截器  拦截所有请求  验证token是否有效
@Component
public class JwtInterceptor  implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 从请求头中获取token
        String token = request.getHeader("Authorization");
        // 2. 验证token
        if (token == null || !token.startsWith("Bearer ")) {
            return false;
        }
        // 3. 提取token（去掉"Bearer "前缀）
        token = token.substring(7);
        // 4. 验证token
        try {
            // 4. 验证token
            String username = jwtUtil.verifyToken(token);

            // 5. 检查token是否过期
            if (jwtUtil.isTokenExpired(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("token已过期");
                return false;
            }

            // 6. token验证成功，可以将用户信息存入请求属性中，供后续处理使用
            request.setAttribute("username", username);
            return true;
        } catch (JWTVerificationException e) {
            // 7. token验证失败
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("无效的token");
            return false;
        }
    }


}
